/**
 * Ajax请求
 * @param string url
 * @param object params
 * @param GET|POST type
 * @param function onSuccess
 * @param function onFail
 *
 * @returns XMLHttp
 */
function toAjax(url, params, type, onSuccess, onFail, onComplete, dom) {
    $.ajax({
        type: type,
        url: url,
        data: params,
        success: onSuccess,
        dataType: "json",
        error: onFail,
        complete: onComplete,
    });

}
var toUpYun ={
    dom : ''
};

/**
 * 上传组件
 * @param filepath 文件上传的目录
 * @param dom 绑定的div的id
 * @param accept 文件检索类型
 * @param ext 文件保存的扩展名，默认为jpg
 * @param value 文件的值 update by abao on 2018-05-21
 */
toUpYun.init =  function(filepath,dom,accept,ext,value) {
    if(typeof(value) == undefined) {
        value = '';
    }
    this.dom = dom;

    $('#'+dom).html("<div style=\"overflow: hidden; width:0; height:0;\"> "+
        " <input name=\"file\" type=\"file\" accept=\""+accept+"\" id=\""+dom+"_file_btn\" disabled /></div>"+
        "<div  class=\"toUpYun_bar\"><input type='hidden' name=\""+dom+"_src\" id=\""+dom+"_src\" value=\""+value+"\" /><div id=\""+dom+"_file\" class=\"toUpYun_btn\">选择文件</div> <div id=\""+dom+"_btn\" class=\"toUpYun_btn_file\">上传文件</div></div>"+
        "<div id='"+dom+"_res'  class=\"toUpYun_res\"></div>");

    $('#'+dom+'_file').on('click', function () {
        $('#'+dom+'_file_btn').removeAttr('disabled').click().attr('disabled',true);
    });

    $('#'+dom+'_btn').on('click', function () {
        $('#'+dom+ '_res').html('开始上传...');
        $.getJSON('/merchant/Upload/uploadApi.html?filepath='+ filepath+'&filetype='+ext, function (data) {
            var file = $('#'+dom+'_file_btn').get(0).files[0];
            data = JSON.parse(data);
            var uploadData = new FormData();
            uploadData.append('file',file);
            uploadData.append('policy', data.policy);
            console.log(data.policy);
            uploadData.append('authorization', data.authorization);
            console.log( data.authorization);
            console.log(uploadData);
            $.ajax({
                url: 'http://v0.api.upyun.com/hxtz-8518',
                type: 'POST',
                data: uploadData,
                cache: false,
                processData: false,
                contentType: false,
                xhr:xhrOnProgress(function(e){
                    var percent=Math.floor(100*e.loaded / e.total);//计算百分比
                    if(percent < 100){
                        $(dom+'_res').html('开始上传...'+  percent +"%" );
                    }
                    else{
                        $(dom+'_res').html('等待文件地址回传...');
                    }
                })
            }).done(function(data, textStatus) {
                data = JSON.parse(data);
                $('#'+dom+ '_src').val(data.url);
                $('#'+dom+ '_res').html('上传成功！')
            }).fail(function(res, textStatus, error) {
                try {
                    console.log(res);
                    var body = JSON.parse(res.responseText);
                   $('#'+dom+ '_res').html('上传失败...原因:'+ body.message);
                } catch(e) {
                    console.error(e);
                }
            })
        });
    });
};

var xhrOnProgress=function(fun) {
    xhrOnProgress.onprogress = fun; //绑定监听
    //使用闭包实现监听绑
    return function() {
        //通过$.ajaxSettings.xhr();获得XMLHttpRequest对象
        var xhr = $.ajaxSettings.xhr();
        //判断监听函数是否为函数
        if (typeof xhrOnProgress.onprogress !== 'function')
            return xhr;
        //如果有监听函数并且xhr对象支持绑定时就把监听函数绑定上去
        if (xhrOnProgress.onprogress && xhr.upload) {
            xhr.upload.onprogress = xhrOnProgress.onprogress;
        }
        return xhr;
    }
};
